package com.tanhua.manage.service;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tanhua.manage.domain.AnalysisByDay;
import com.tanhua.manage.mapper.AnalysisByDayMapper;
import com.tanhua.manage.mapper.LogMapper;
import com.tanhua.manage.utils.ComputeUtil;
import com.tanhua.manage.vo.AnalysisSummaryVo;
import com.tanhua.manage.vo.YearVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

@Service
public class AnalysisByDayService extends ServiceImpl<AnalysisByDayMapper, AnalysisByDay> {
    @Autowired
    private AnalysisByDayMapper analysisByDayMapper;
    @Autowired
    private LogMapper logMapper;

    /**
     * 接口名称：概要统计信息
     * @return
     */
    public ResponseEntity<Object> summary() {
        // 1. 查询累计注册用户：SELECT SUM(num_registered) num_registered FROM tb_analysis_by_day
        AnalysisByDay analysisByDay =
                query().select("SUM(num_registered) num_registered").one();
        // 1.1 获取累计用户
        Integer numRegistered = analysisByDay.getNumRegistered();

        // 2. 根据日期，查询今天的新增用户、登陆次数、活跃用户
        // 2.1 获取今天的日期
        Date now = new Date();
        String today = new SimpleDateFormat("yyyy-MM-dd").format(now);
        AnalysisByDay todayAnalysis = query().eq("record_date", today).one();
        // 2.2 获取今天新增用户、登陆次数、活跃用户
        Integer todayRegister = todayAnalysis.getNumRegistered();
        Integer todayLogin = todayAnalysis.getNumLogin();
        Integer todayActive = todayAnalysis.getNumActive();

        // 3. 查询昨天的新增用户、登陆次数、活跃用户
        // 3.1 获取昨天的日期
        String yes = ComputeUtil.offsetDay(now, -1);
        // 3.2 根据日期查询
        AnalysisByDay yesAnalysis = query().eq("record_date", yes).one();
        // 3.2 获取昨天新增用户、登陆次数、活跃用户
        Integer yesRegister = yesAnalysis.getNumRegistered();
        Integer yesLogin = yesAnalysis.getNumLogin();
        Integer yesActive = yesAnalysis.getNumActive();

        // 4. 查询过去7天活跃、过去30天活跃
        Long day7 = analysisByDayMapper.findNumActiveByDate(ComputeUtil.offsetDay(now,-7),today);
        Long day30 = analysisByDayMapper.findNumActiveByDate(ComputeUtil.offsetDay(now,-30),today);

        // 5.创建vo并返回
        AnalysisSummaryVo vo = new AnalysisSummaryVo();
        // 设置累计用户数
        vo.setCumulativeUsers(numRegistered.longValue());
        // 设置新增用户、登陆次数、活跃用户
        vo.setNewUsersToday(todayRegister.longValue());
        vo.setLoginTimesToday(todayLogin.longValue());
        vo.setActiveUsersToday(todayActive.longValue());
        // 设置新增用户、登陆次数、活跃用户的环比
        vo.setNewUsersTodayRate(ComputeUtil.computeRate(todayRegister,yesRegister));
        vo.setLoginTimesTodayRate(ComputeUtil.computeRate(todayLogin,yesLogin));
        vo.setActiveUsersTodayRate(ComputeUtil.computeRate(todayActive,yesActive));
        // 设置过去7天活跃、过去30天活跃
        vo.setActivePassWeek(day7);
        vo.setActivePassMonth(day30);
        // 返回
        return ResponseEntity.ok(vo);
    }

    /**
     * 查询日志表(tb_log)数据，更新到日表中（tb_analysis_by_day）
     */
    public void analysis() {
        //1. 根据当前时间查询日表数据 tb_analysis_by_day
        //1.1 获取今天的日期
        Date date = new Date();
        String today = new SimpleDateFormat("yyyy-MM-dd").format(date);
        //1.2 根据今天的日期查询日表
        AnalysisByDay analysisByDay = query().eq("record_date", today).one();

        //2. 如果没有查到，说明还没有今天的日表统计的数据，执行插入
        if (analysisByDay == null) {
            analysisByDay = new AnalysisByDay();
            analysisByDay.setRecordDate(date);
            analysisByDay.setUpdated(new Date());
            analysisByDay.setCreated(new Date());
            // 执行插入
            analysisByDayMapper.insert(analysisByDay);
        }

        //3. 更新日表数据 tb_analysis_by_day
        //3.1 查询日志表，获取数据
        //3.1.1 查询新注册用户
        Long numRegister = logMapper.queryNumsByType("0102",today);
        //3.1.2 查询登陆次数
        Long numLogin = logMapper.queryNumsByType("0101",today);
        //3.1.3 查询活跃用户数
        Long numActive = logMapper.queryNumsByTime(today);
        //3.1.4 查询次日留存用户数 (昨天注册，今天登陆)
        // 获取昨天日期
        String yesterday = ComputeUtil.offsetDay(date,-1);
        // 查询
        Long numRetention1d = logMapper.queryNumRetention1d(today,yesterday);

        //3.2 更新到日表中
        //3.2.1 新注册用户
        analysisByDay.setNumRegistered(numRegister.intValue());
        //3.2.2 登陆次数
        analysisByDay.setNumLogin(numLogin.intValue());
        //3.2.3 活跃用户数
        analysisByDay.setNumActive(numActive.intValue());
        //3.2.4 次日留存用户数
        analysisByDay.setNumRetention1d(numRetention1d.intValue());
        //3.2.5 更新
        analysisByDayMapper.updateById(analysisByDay);
    }

    public ResponseEntity<Object> findUsers(String sd, String ed, Integer type) {
        /*sd = "2019-01-01";
        ed = "2020-01-01";*/
        YearVo yearVo = new YearVo();
        String types;
        switch (type){
            case 101:
                //新增
                types="num_registered as amount";
                yearVo=getFindYear(sd,ed,types);
                break;
            case 102:
                //活跃用户
                types="num_active as amount";
                yearVo=getFindYear(sd,ed,types);
                break;
            case 103:
                //次日留存
                types="num_retention1d as amount";
                yearVo=getFindYear(sd,ed,types);
                break;
        }
        return ResponseEntity.ok(yearVo);
    }

    private YearVo getFindYear(String sd, String ed, String types) {
        //开始
        String start = new SimpleDateFormat("yyyy-MM-dd").format(new Date(Long.valueOf(sd)));
        //结束
        String end = new SimpleDateFormat("yyyy-MM-dd").format(new Date(Long.valueOf(ed)));
        //今年的数据
        List<Map<String, Object>> thisYear;
        QueryWrapper<AnalysisByDay> NewWrapper = new QueryWrapper<>();
        NewWrapper.select("record_date as title", types).le("record_date", end).ge("record_date", start);
        thisYear= analysisByDayMapper.selectMaps(NewWrapper);
        //thisYear= analysisByDayMapper.selectThisYear(types,end,start);
        //去年的数据
        List<Map<String, Object>> lastYear;
        //计算去年时间
        String yearAnd = ComputeUtil.offsetYear(end);
        String yearStart = ComputeUtil.offsetYear(start);
        NewWrapper.select("record_date as title", types).le("record_date", yearAnd).ge("record_date", yearStart);
        lastYear= analysisByDayMapper.selectMaps(NewWrapper);
        return new YearVo(thisYear,lastYear);
    }
}
